"""
配置管理工具类
用于读取和管理测试配置信息
"""

import yaml
import os
from typing import Dict, Any
from loguru import logger


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_path: str = "config/devices.yaml"):
        """
        初始化配置管理器
        
        Args:
            config_path: 配置文件路径
        """
        self.config_path = config_path
        self.config = self._load_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """
        加载配置文件
        
        Returns:
            配置字典
        """
        try:
            if not os.path.exists(self.config_path):
                logger.error(f"配置文件不存在: {self.config_path}")
                return {}
            
            with open(self.config_path, 'r', encoding='utf-8') as file:
                config = yaml.safe_load(file)
                logger.info(f"成功加载配置文件: {self.config_path}")
                return config
        except Exception as e:
            logger.error(f"加载配置文件失败: {e}")
            return {}
    
    def get_device_config(self, platform: str) -> Dict[str, Any]:
        """
        获取指定平台的设备配置
        
        Args:
            platform: 平台名称 (android/ios)
            
        Returns:
            设备配置字典
        """
        devices = self.config.get('devices', {})
        device_config = devices.get(platform.lower(), {})
        
        if not device_config:
            logger.warning(f"未找到平台 {platform} 的配置")
        
        return device_config
    
    def get_appium_server_config(self) -> Dict[str, Any]:
        """
        获取Appium服务器配置
        
        Returns:
            Appium服务器配置字典
        """
        return self.config.get('appium_server', {})
    
    def get_test_config(self) -> Dict[str, Any]:
        """
        获取测试配置
        
        Returns:
            测试配置字典
        """
        return self.config.get('test_config', {})
    
    def get_server_url(self) -> str:
        """
        获取Appium服务器URL
        
        Returns:
            服务器URL
        """
        server_config = self.get_appium_server_config()
        host = server_config.get('host', '127.0.0.1')
        port = server_config.get('port', 4723)
        path = server_config.get('path', '/wd/hub')
        
        return f"http://{host}:{port}{path}"
    
    def reload_config(self) -> None:
        """重新加载配置文件"""
        self.config = self._load_config()
        logger.info("配置文件已重新加载")


# 全局配置管理器实例
config_manager = ConfigManager() 